/*
 * Copyright (c) 2007 Compl Yue Still, All Rights Reserved.
 */

package hbi.wire.java.guest;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ForecastedType
{

    public final Class<?> javaClass;

    public final int index;

    private final GuestEnd guestEnd;

    public ForecastedType(Class<?> javaClass, int index, GuestEnd guestEnd)
    {
        this.javaClass = javaClass;
        this.index = index;
        this.guestEnd = guestEnd;
    }

    // assume already properly synchronized from outside

    private final Map<Method, Short> methods = new HashMap<Method, Short>();

    public short getMethodIndex(Method method)
    {
        if (methods.size() >= Short.MAX_VALUE)
            throw new RuntimeException("Too many methods.");
        try
        {
            Short idx = methods.get(method);
            if (idx == null)
            {
                guestEnd.writeByte('m');
                guestEnd.writeUTF(method.getName() + '#'
                    + method.getParameterTypes().length);
                methods.put(method, idx = (short) methods.size());
            }
            return idx;
        }
        catch (IOException e)
        {
            // TODO: throw an exception handled by the framework
            throw new RuntimeException(e);
        }
    }

}
